<template>
  <div class="user">
    <ListTab v-if="!showMobilePage" show-header >
      <div slot="head" class="title-name">用户设置</div>
    </ListTab>
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" class="list-top">
        <div style="flex:1;display:flex;margin-bottom:16px;" class="query-form">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :is-show-filter="isShowFilter"
            :filter-list="filterList"
            show-search-btn
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
          <span style="flex:1;"/>
          <create-button
            v-if="hasRouteAuth('crm:userList:add')"
            :icon="'el-icon-plus'"
            :create-link-name="createLinkName"
            add-name="新增" />
          <el-button
            v-if="hasRouteAuth('crm:userList:syncStructure')"
            :loading="syncLoading"
            class="search-btn-style sync-btn"
            plain
            style="margin-left: 10px"
            type="primary"
            size="small"
            @click="handleSync">立即同步架构数据</el-button>
        </div>
      </div>
      <el-row v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.items.length > 0"
          :data="list.items"
          :height="setTableHeight"
          :row-height="49"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @sort-change="sortMethod">
          <u-table-column align="left" label="工号" width="100">
            <template slot-scope="scope">
              {{ scope.row.jobNumber || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="头像" width="60">
            <template slot-scope="scope">
              <UserCard :user-data="{ avatar: scope.row.avatar, id: scope.row.id }" is-border class="user-avatar-box" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="姓名" width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.userName"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="职位" width="130">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.post"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="邮箱" min-width="160">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.email"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="微信号" min-width="140">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.wxCode"/>
            </template>
          </u-table-column>
          <u-table-column align="left" label="部门" min-width="130">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.departmentName" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">
                  <div v-for="(i, index) in scope.row.departmentDetail" :key="index">{{ i }}</div>
                </div>
                <span class="ellipsisOne">{{ scope.row.departmentName.join(',') || '--' }}</span>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <!-- <el-table-column align="left" label="子部门" min-width="130">
            <template slot-scope="scope">
              <template v-if="scope.row.subDepartment && scope.row.subDepartment.length">
                <div v-for="(item, index) in scope.row.subDepartment" :key="index" class="dept-name">
                  {{ item.name }}<span v-if="item.name" class="division"> / &nbsp;</span>
                </div>
              </template>
              <div v-else>--</div>
            </template>
          </el-table-column> -->
          <u-table-column align="left" label="在职状态" min-width="100">
            <template slot-scope="scope">
              <div
                :class="scope.row.jobStatus === 1 ? 'status-on' : 'status-off'"
                style="padding-left: 10px;">
                {{ scope.row.jobStatus === 1 ? '在职' : '离职' }}
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="入职时间" prop="entryTime" sortable="custom" min-width="110">
            <template slot-scope="scope">
              <span v-if="scope.row.entryTime">{{ scope.row.entryTime | standardFormat('YYYY/MM/DD') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="离职时间" prop="dimissionTime" sortable="custom" min-width="110">
            <template slot-scope="scope">
              <span v-if="scope.row.dimissionTime">{{ scope.row.dimissionTime | standardFormat('YYYY/MM/DD') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="right" label="借款金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.financialInfo"
                :real-val="scope.row.financialInfo.loanAmount"
                :price="scope.row.financialInfo.loanAmount / 100"
                placement="top-end" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="right" label="冲抵借款欠额(元)" min-width="140">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.financialInfo"
                :real-val="scope.row.financialInfo.offsetLoanAmount"
                :price="scope.row.financialInfo.offsetLoanAmount / 100"
                placement="top-end" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="right" label="还款金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.financialInfo"
                :real-val="scope.row.financialInfo.repaymentAmount"
                :price="scope.row.financialInfo.repaymentAmount / 100"
                placement="top-end" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="right" label="转交欠款(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.financialInfo"
                :real-val="scope.row.financialInfo.transferArrearsAmount"
                :price="scope.row.financialInfo.transferArrearsAmount / 100"
                placement="top-end" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="right" label="被转交欠款(元)" min-width="130">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.financialInfo"
                :real-val="scope.row.financialInfo.transfereeArrearsAmount"
                :price="scope.row.financialInfo.transfereeArrearsAmount / 100"
                placement="top-end" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="right" label="借款欠额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.financialInfo"
                :real-val="scope.row.financialInfo.owedAmount"
                :price="scope.row.financialInfo.owedAmount / 100"
                placement="top-end" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="电话" min-width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.phone" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="城市" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.city" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="最后登录时间" min-width="155">
            <template slot-scope="scope">
              <span v-if="scope.row.lastLoginTime">{{ scope.row.lastLoginTime | standardFormat('YYYY/MM/DD HH:mm') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="同步时间" min-width="155">
            <template slot-scope="scope">
              <span v-if="scope.row.updateTime">{{ scope.row.updateTime | standardFormat('YYYY/MM/DD HH:mm') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="155">
            <template slot-scope="scope">
              {{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="状态" width="80">
            <template slot-scope="scope">
              <div>
                <el-switch
                  v-model="scope.row.userStatus"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#406EFF"
                  inactive-color="#cccccc"
                  @change="switchStatus(scope.row, $event)"
                />
              </div>
            </template>
          </u-table-column>
          <u-table-column :width="showMobilePage ? 64 : 100" label="操作" fixed="right">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex;">
                <el-button type="text" @click="toDetail(scope)"><span style="font-size:14px;">查看</span></el-button>
                <el-button
                  v-if="hasRouteAuth('crm:userList:edit')"
                  :class="{'border-left': hasRouteAuth('crm:userList:edit')}"
                  type="text"
                  @click="toEdit(scope)">
                  <span style="font-size:14px;"> 编辑</span>
                </el-button>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item tyle="width:90px;text-align: center" @click.native="toDetail(scope)">
                  <div style="font-size: 14px">查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('crm:userList:edit')" style="width:90px;text-align: center" @click.native="toEdit(scope)">
                  <div>编辑</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </el-row>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination>
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :is-show-filter="isShowFilter"
            :filter-list="filterList"
            show-mobile-icon
            show-search-btn
            class="FilterTool mobile-filter-form"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
          <el-button
            v-if="hasRouteAuth('crm:userList:syncStructure')"
            :loading="syncLoading"
            class="search-btn-style sync-btn"
            style="height: 35px; padding: 0 12px; flex: 1; margin-right: 10px"
            plain
            type="primary"
            size="small"
            @click="handleSync"
          >立即同步架构数据</el-button>
          <CreateBtn
            v-if="hasRouteAuth('crm:userList:add')"
            mobile-table
            style="width: 100%"
            text="新增"
            @click.native="toCreate"
          />
        </template>
        <template v-else>
          <span style="flex:1;"/>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import { hasRouteAuth } from '@/utils/permission';
import { getList, changeStatus, syncStructure } from '@/api/user';
import { getDepartmentAll } from '@/api/config';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import CreateButton from '@/components/CreateButton';
import CreateBtn from '@/components/Common/baseComponent/createBtn';
import ListTab from '@/components/ListTab';
import Title from '@/components/Title';
import UserCard from '@/components/Common/userCard';
import { standardFormat } from '@/filters/date';
import { paramsAryToStr, paramsRangeFormat } from '@/utils/paramsFormat';
import clearIcon from '@/assets/medium/clear.png';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { showModal } from '@/utils/message';
import { mapState } from 'vuex';

export default {
  filters: {
    standardFormat,
    deptNameFilter(list) {
      const ans = [];
      list.forEach(i => {
        ans.push(i.name);
      });
      return ans.join(',');
    }
  },
  components: {
    CreateButton,
    ListTab,
    Title,
    CreateBtn,
    UserCard,
    EmptyPlaceholder
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      clearIcon,
      addName: '新增用户',
      createLinkName: 'createUser',
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      deptTreeList: [],
      isUmyTable: true,
      syncLoading: false,
      isShowFilter: false,
      listLoading: false,
      paramsObj: {},
      sortName: '',
      sortType: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 148 : 188;
    },
    userOptions() {
      return [
        { value: -1, label: '全部' },
        { value: 0, label: '禁用' },
        { value: 1, label: '启用' }
      ];
    },
    jobStatusOptions() {
      return [
        { value: 0, label: '离职' },
        { value: 1, label: '在职' }
      ];
    },
    filterList() {
      return [
        // 输入框
        { keyword: 'userName', name: '姓名', labelWidth: '100px', type: 'input' },
        { keyword: 'jobNumber', name: '工号', labelWidth: '100px', type: 'input' },
        { keyword: 'phone', name: '电话', labelWidth: '100px', type: 'input' },
        { keyword: 'city', name: '城市', labelWidth: '100px', type: 'input' },
        { keyword: 'post', name: '职位', labelWidth: '100px', type: 'input' },
        { keyword: 'wxCode', name: '微信号', labelWidth: '100px', type: 'input' },
        {
          keyword: 'loanAmount', name: '借款金额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999
        }, {
          keyword: 'offsetLoanAmount', name: '冲抵借款欠额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999
        }, {
          keyword: 'repaymentAmount', name: '还款金额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999
        }, {
          keyword: 'transferArrearsAmount', name: '转交欠款', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999
        }, {
          keyword: 'transfereeArrearsAmount', name: '被转交欠款', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999
        }, {
          keyword: 'owedAmount', name: '借款欠额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999
        },
        { keyword: 'entryTime', name: '入职时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'dimissionTime', name: '离职时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        // 下拉
        { keyword: 'userStatus', name: '状态', type: 'select', options: this.userOptions },
        { keyword: 'jobStatus', name: '在职状态', type: 'select', options: this.jobStatusOptions },
        { keyword: 'departmentIds', name: '部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList }
      ];
    },
    arrayKeyArr() {
      return ['departmentIds'];
    },
    rangeKeyArr() {
      return [{
        attr: 'loanAmount',
        start: 'loanAmountStart',
        end: 'loanAmountEnd',
        type: 'moneyFixed'
      }, {
        attr: 'offsetLoanAmount',
        start: 'offsetLoanAmountStart',
        end: 'offsetLoanAmountEnd',
        type: 'moneyFixed'
      }, {
        attr: 'repaymentAmount',
        start: 'repaymentAmountStart',
        end: 'repaymentAmountEnd',
        type: 'moneyFixed'
      }, {
        attr: 'transferArrearsAmount',
        start: 'transferArrearsAmountStart',
        end: 'transferArrearsAmountEnd',
        type: 'moneyFixed'
      }, {
        attr: 'transfereeArrearsAmount',
        start: 'transfereeArrearsAmountStart',
        end: 'transfereeArrearsAmountEnd',
        type: 'moneyFixed'
      }, {
        attr: 'owedAmount',
        start: 'owedAmountStart',
        end: 'owedAmountEnd',
        type: 'moneyFixed'
      }, {
        attr: 'entryTime',
        start: 'entryTimeStart',
        end: 'entryTimeEnd',
        type: 'time',
        addTime: true
      }, {
        attr: 'dimissionTime',
        start: 'dimissionTimeStart',
        end: 'dimissionTimeEnd',
        type: 'time',
        addTime: true
      }];
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editUser' || from.name === 'userDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  created() {
    this.queryDeptTreeList();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      this.fetchData(true);
    } else {
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
  },
  methods: {
    hasRouteAuth,
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.listLoading = true;
      getList(this.page, this.perPage, params).then(({ data = {}} = {}) => {
        (data.items || []).forEach(item => {
          item.subDepartment.forEach((val, index) => {
            if (val.id === 0) {
              item.subDepartment.splice(index, 1);
            }
          });
        });
        this.list = data;
      }).catch(e => {
        console.error(e);
      }).finally(() => {
        this.list.isInit = false;
        this.listLoading = false;
      });
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      return params;
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    toCreate() {
      this.$router.push({ name: this.createLinkName });
    },
    toDetail(scope) {
      this.$router.push({
        name: 'userDetail',
        params: { userId: scope.row.id }
      });
    },
    toEdit(scope) {
      this.$router.push({
        name: 'editUser',
        params: { userId: scope.row.id }
      });
    },
    async switchStatus(item, userStatus) {
      const params = {
        userStatus: userStatus
      };
      try {
        const res = await changeStatus(item.id, params);
        if (res.code === 200) {
          item.userStatus = params.userStatus;
        }
      } catch (error) {
        item.userStatus = params.userStatus === 0 ? 1 : 0;
      }
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    handleSync() {
      showModal('请确认是否立即同步人员及架构数据').then(_ => {
        this.syncLoading = true;
        syncStructure().then(res => {
          if (res.code === 200) {
            this.syncLoading = false;
            this.fetchData();
          }
        }).catch(err => {
          console.log(err);
        });
      }).catch(_ => null);
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData();
    }
  }
};
</script>

<style  lang="scss" scoped>
.title-name {
  white-space: nowrap;
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: center;
}
.user {
  &::v-deep {
    .el-select__caret {
      line-height: 32px;
    }
    .query-form input {
      width: 120px;
      color: #333;
    }
    tr {
      td:nth-child(2) {
        padding: 0 !important;
      }
    }
  }
  .user-avatar-box {
    ::v-deep {
      img {
        cursor: pointer !important;
      }
    }
  }
  .query-form {
    .el-form-item {
      margin-right: 16px;
    }
    .input-width-select-bg {
      & ::v-deep {
        .el-input__inner:last-child {
          background: #fff;
        }
      }
      .changeStatus {
        & ::v-deep {
          .el-input input {
            width: 80px;
          }
        }
      }
    }
    .query-button {
      padding-top: 0;
    }
  }
  .table-list {
    margin: 16px 16px 0 16px;
    // border:1px solid #eee;
    // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
    // border-radius:12px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .el-row {
      padding: 0;
    }
  }
  .el-table {
    font-size: 14px;
    .operate-btn .cell {
      display: flex;
      justify-content: space-around;
      margin-right: 7px;
      padding: 0;
    }
    .dept-name {
      display: inline-block;
      &:last-child {
        .division {
          display: none;
        }
      }
    }
  }
  .el-table__body-wrapper .user-status-forbidden {
    color: red;
  }
  .el-table__body-wrapper .user-status-normal {
    color: green
  }
  .border-left {
    position: relative;
    padding-left: 12px;
    // margin-left: 6px;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
}
.user-eidt-tooltip {
  padding: 5px 10px;
  .popper__arrow {
    top: 6px !important;
  }
}
.list-top {
  display: flex;
  align-items: center;
  .list-title {
    flex:1;
  }
  .btn-right{
    display: flex;
    .btn {
      margin-left: 10px;
    }
  }
}
.status-on, .status-off {
  &::before {
    content: '';
    width: 4px;
    height: 4px;
    position: absolute;
    left: 10px;
    top: 10px;
    border-radius: 50%;
  }
}
.status-on {
  &::before {
    background-color: rgb(49, 204, 156);
  }
}
.status-off {
  &::before {
    background-color: #999;
  }
}
.sync-btn {
  height: 32px;
}
.mobile-filter-content {
  display: flex;
  &::v-deep {
    .el-input--suffix {
      min-width: 68px;
      color: #333;
    }
  }
}
</style>
